package com.yunshang.shoppingmall.ShopTask.Task.Hsys;

import com.alibaba.fastjson.JSON;
import com.yunshang.shoppingmall.Methods.FinaceMethods;
import com.yunshang.shoppingmall.Methods.UserMethods;
import com.yunshang.shoppingmall.Methods.UserNoMethods;
import com.yunshang.shoppingmall.ShopTask.ShopState;
import com.yunshang.shoppingmall.common.HttpRequest;
import com.yunshang.shoppingmall.entity.Hsys.HsysUserData;
import com.yunshang.shoppingmall.entity.Hsys.HsysUserRoot;
import com.yunshang.shoppingmall.entity.ShopTaskState;
import com.yunshang.shoppingmall.entity.User;
import com.yunshang.shoppingmall.entity.UserNo;
import com.yunshang.shoppingmall.service.SysUserNoService;
import com.yunshang.shoppingmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class HsysUser {

    @Autowired
    SysUserNoService userNoService;

    @Autowired
    UserService userService;

    private List<HsysUserData> hsysUserList;

    private Dictionary<String, User> dicUserList = new Hashtable<String, User>();
    private Dictionary<String, UserNo> dicUserNoList = new Hashtable<String, UserNo>();

    public void getUser() {
        ShopState.SetMsg("荟生用户同步","开始读取荟生数据",0,0,0,0,0);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        Date t1 = c.getTime();
        String endTime =formatter.format(c.getTime());
        c.add(Calendar.HOUR_OF_DAY, -1);
        Date t2 = c.getTime();
        String startTime =formatter.format(c.getTime());
        String hsysUrl = "http://yc.huisheng2688.com/hsycMgr/app/batchGetUserInfo.do";
        String param = "startTime=" + startTime
                + "&endTime=" + endTime
                + "&encryptStr=60f5a3c2ab917609282ebaafc6365589"
                + "&clientIp=127.0.0.1";
        System.out.println(param);
        String json = HttpRequest.sendPost(hsysUrl, param);

        //String json = "{\"type\":\"1\",\"msg\":null,\"data\":[{\"userno\":\"hyqy168\",\"cellphone\":\"18245059596\",\"password\":null,\"level\":2,\"angeluserno\":\"Hsj168\",\"azangeluserno\":\"hsj168\",\"username\":\"殷庆云\",\"createtime\":\"2018-10-18 09:28:58\"},{\"userno\":\"H221412\",\"cellphone\":\"13386979339\",\"password\":null,\"level\":2,\"angeluserno\":\"zcc845758\",\"azangeluserno\":\"H600412\",\"username\":\"张坤发\",\"createtime\":\"2018-10-18 09:36:23\"},{\"userno\":\"H310469\",\"cellphone\":\"17382310469\",\"password\":null,\"level\":2,\"angeluserno\":\"c260333\",\"azangeluserno\":\"H998603085\",\"username\":\"杨必华\",\"createtime\":\"2018-10-18 09:47:53\"},{\"userno\":\"H202385\",\"cellphone\":\"18785202385\",\"password\":null,\"level\":2,\"angeluserno\":\"H535427\",\"azangeluserno\":\"H188625\",\"username\":\"兰燕\",\"createtime\":\"2018-10-18 09:53:41\"}],\"param\":null,\"success\":true}";
        System.out.println("JSON:"+json);
        HsysUserRoot hsysUserRoot = JSON.parseObject(json, HsysUserRoot.class);
        hsysUserList = hsysUserRoot.getData();
        if(hsysUserList!=null)
        {
            total = hsysUserList.size();
            ShopState.SetMsg("荟生用户同步","荟生数据",total,0,0,0,0);
            List<User> userList = UserMethods.getUser();
            if (userList != null) {
                System.out.println("用户数量"+userList.size());
                for (int j = 0; j < userList.size(); j++) {
                    try {
                        dicUserList.put(userList.get(j).getPhone(), userList.get(j));
                    }catch (Exception ex)
                    {}
                }
                System.out.println("W");
            }
            System.out.println("A");
            List<UserNo> userNoList = UserNoMethods.getUserNo();
            if (userNoList != null) {
                System.out.println("用户编号数量"+userNoList.size());
                for (int j = 0; j < userNoList.size(); j++) {
                    dicUserNoList.put(userNoList.get(j).getUserNo().toLowerCase(), userNoList.get(j));
                }
            }
            System.out.println("B");
            ShopState.SetMsg("荟生用户同步", "数据读取完成", total, location, suc, fail, skip);

            //准备同步
            location=0;
            suc=0;
            fail=0;
            skip=0;

            //开始同步
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    HsysData();
                }
            }, 1000);

        }
        else {
            ShopState.SetMsg("荟生用户同步", "完成", total, location, suc, fail, skip);
            ShopTaskState.setComplete(false);
        }
    }

    private int total=0;
    private int location=0;
    private int suc=0;
    private int fail=0;
    private int skip=0;

    public void HsysData() {
        if (location < total) {
            ShopState.SetMsg("荟生用户同步", "编号：" + hsysUserList.get(location).getUserno() + " 姓名：" + hsysUserList.get(location).getUsername() + "身份证：" + hsysUserList.get(location).getIdcard(), total, location + 1, suc, fail, skip);

            //查询是否存在手机号
            //如果存在，则返回ID号
            int userId = 0;
            if (dicUserNoList.size() > 0) {
                if (hsysUserList.get(location).getCellphone() != null) {
                    if (hsysUserList.get(location).getCellphone() != null && hsysUserList.get(location).getCellphone().length() == 11) {
                        User userDic = dicUserList.get(hsysUserList.get(location).getCellphone());
                        if (userDic != null) {
                            userId = userDic.getUserId();
                        }
                    } else {
                        User userDic = dicUserList.get(hsysUserList.get(location).getUserno());
                        if (userDic != null) {
                            userId = userDic.getUserId();
                        }
                    }
                }
            }

            //如果部存在，则添加数据
            if (userId == 0) {
                User user = new User();
                if (hsysUserList.get(location).getUsername().length() == 0) {
                    user.setUserName(hsysUserList.get(location).getUserno());
                } else {
                    user.setUserName(hsysUserList.get(location).getUsername());
                }
                user.setCardId(hsysUserList.get(location).getIdcard());
                System.out.println(hsysUserList.get(location).getCellphone());
                if (hsysUserList.get(location).getCellphone() != null && hsysUserList.get(location).getCellphone().length() == 11) {
                    user.setPhone(hsysUserList.get(location).getCellphone());
                } else {
                    user.setPhone(hsysUserList.get(location).getUserno());
                }
                Timestamp ts = new Timestamp(System.currentTimeMillis());
                String tsStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(hsysUserList.get(location).getCreatetime());
                System.out.println(tsStr);
                try {
                    ts = Timestamp.valueOf(tsStr);
                    System.out.println(ts);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                user.setRegisterTime(ts);
                user.setRecommend(0);
                user.setSort(100);
                User user1 = UserMethods.insert(user);
                userId = user.getUserId();
                System.out.println("用户ID"+userId);
                System.out.println("用户ID"+user1.getUserId());
                if (hsysUserList.get(location).getCellphone() != null && hsysUserList.get(location).getCellphone().length() == 11) {
                    dicUserList.put(hsysUserList.get(location).getCellphone(), user1);
                } else {
                    dicUserList.put(hsysUserList.get(location).getUserno(), user1);
                }
                System.out.println(userId);

            }

            if (userId == 0) {
                System.out.println(hsysUserList.get(location).getUserno() + "失败");
                fail++;
                ShopState.SetMsg("荟生用户同步", "编号：" + hsysUserList.get(location).getUserno() +"失败", total, location + 1, suc, fail, skip);
            } else {
                boolean blUserNo = true;
                //查找是否已经存在
                UserNo usernoDic = dicUserNoList.get(hsysUserList.get(location).getUserno());
                if (usernoDic != null) {
                    System.out.println("Y:用户编号"+hsysUserList.get(location).getUserno());
                    blUserNo = false;
                    skip++;
                    ShopState.SetMsg("荟生用户同步", "编号：" + hsysUserList.get(location).getUserno() +"跳过", total, location + 1, suc, fail, skip);
                }

                if (blUserNo) {
                    UserNo userNo = new UserNo();
                    userNo.setUserId(userId);
                    userNo.setUserNo(hsysUserList.get(location).getUserno());
                    userNo.setName(hsysUserList.get(location).getUsername());
                    if (hsysUserList.get(location).getPassword() != null) {
                        userNo.setPwd(hsysUserList.get(location).getPassword());
                    }
                    Timestamp ts = new Timestamp(System.currentTimeMillis());
                    String tsStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(hsysUserList.get(location).getCreatetime());
                    System.out.println(tsStr);
                    try {
                        ts = Timestamp.valueOf(tsStr);
                        System.out.println(ts);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    userNo.setRegisterTime(ts);
                    userNo.setSort(100);

                    userNo.setHsrank(hsysUserList.get(location).getLevel());

                    int rank = 0;
                    int agent = 0;
                    switch (hsysUserList.get(location).getLevel()) {
                        case 0:
                            rank = 19;
                            break;
                        case 1:
                            rank = 16;
                            agent=1;
                            break;
                        case 2:
                            rank = 17;
                            agent=1;
                            break;
                        case 10:
                            rank = 17;
                            agent=1;
                            break;
                        case 20:
                            rank = 21;
                            agent=1;
                            break;
                        case 30:
                            rank = 22;
                            agent=1;
                            break;
                        case 40:
                            agent=1;
                            rank = 22;
                            break;
                        case 401:
                            agent=1;
                            rank = 22;
                            break;
                        default:
                            rank = -1;
                            rank = 1000+hsysUserList.get(location).getLevel();
                            break;
                    }

                    userNo.setRank(rank);
                    userNo.setAgent(agent);
                    //处理分享人
                    int recommend=0;
                    //查找是否存在分享人
                    UserNo userNoRecDic = dicUserNoList.get(hsysUserList.get(location).getAngeluserno().toLowerCase());
                    if (userNoRecDic != null) {
                        recommend = userNoRecDic.getId();
                        System.out.println("用户分享ID"+recommend);
                    }
                    userNo.setRecommend(recommend);

                    UserNo userNo1= UserNoMethods.insert(userNo);
                    System.out.println("用户编号ID"+userNo1.getId());
                    dicUserNoList.put(hsysUserList.get(location).getUserno(), userNo1);

                    //返代金券
                    double amount= 0 ;
                    switch (hsysUserList.get(location).getLevel()) {
                        case 1:
                            amount = 500;
                            break;
                        case 2:
                            amount=1000;
                            break;
                        case 10:
                            amount=4500;
                            break;
                        case 20:
                            amount=12000;
                            break;
                        case 30:
                            amount=45000;
                            break;
                        case 40:
                            amount=90000;
                            break;
                        default:
                            break;
                    }
                    BigDecimal amount4=BigDecimal.valueOf(0.00);
                    amount4 = new BigDecimal(amount);
                    if(amount>0)
                    {
                        FinaceMethods.insertFinaceA(3,amount4,userNo.getId(),"注册赠送hs",-1,115);
                    }


                    suc++;
                    ShopState.SetMsg("荟生用户同步", "编号：" + hsysUserList.get(location).getUserno() +"成功", total, location + 1, suc, fail, skip);
                }
            }




            location++;
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    HsysData();
                }
            }, 1000);
        }
        else
        {
            ShopState.SetMsg("荟生用户同步","完成",total,location,suc,fail,skip);
            ShopTaskState.setComplete(false);
        }
    }
}
